package cn.wolfcode.luowowo.service.impl;


import cn.wolfcode.luowowo.domain.StrategyComment;
import cn.wolfcode.luowowo.domain.StrategyTheme;
import cn.wolfcode.luowowo.query.StrategyCommentObjcet;
import cn.wolfcode.luowowo.repository.StrategyCommentRepository;

import cn.wolfcode.luowowo.service.IStrategyCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private MongoTemplate template;
    @Autowired
    private StrategyCommentRepository strategyCommentRepository;


    @Override
    public StrategyComment get(String id) {
        return  strategyCommentRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyComment> list() {
        return  strategyCommentRepository.findAll();

    }



    @Override
    public Page<StrategyComment> query(StrategyCommentObjcet qo) {
        //创建查询对象
        Query query = new Query();
        //分页查询

        //关键字查询
        if(StringUtils.hasLength(qo.getStrategyId())){
            query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        }
        PageRequest request = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        return DBHelper.query(template,StrategyComment.class,query,request);
    }



    @Override
    public void delete(String id) {
        strategyCommentRepository.deleteById(id);
    }

    @Override
    public void save(StrategyComment strategyComment) {
        strategyComment.setId(null);
        strategyComment.setCreateTime(new Date());
        strategyCommentRepository.save(strategyComment);
    }

    @Override
    public void commentThumb(String cid, String uid) {
        StrategyComment comment = this.get(cid);
        List<String> thumbuplist = comment.getThumbuplist();
        if(!thumbuplist.contains(uid)){
            //不存在的点赞用户，则点赞数+1，在把用户ID存进去
            comment.setThumbupnum(comment.getThumbupnum()+1);
            thumbuplist.add(uid);
        }else{
            //存在的话就点赞数-1，把点赞集合里的ID去除
            comment.setThumbupnum(comment.getThumbupnum()-1);
            thumbuplist.remove(uid);
        }
        strategyCommentRepository.save(comment);
    }


}
